import Vue from "vue";
import VueRouter from "vue-router";
import Home from "@/views/home";
import Search from "@/views/search";
import Login from "@/views/login";
import Register from "@/views/register";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: Home,
    name: "Home",
  },
  // 设参在路由
  // ? 在ts里?可选项
  {
    path: "/search/:keyword",
    component: Search,
    name: "Search",
    // 路由的映射：
    // props，布尔型，只能映射params参数
    // 对象类型：只能映射自定义属性
    // 函数类型：可以映射所有
    // props: true,
    // props: {
    //   name: "子心",
    //   age: 44,
    // },
    props: (route) => {
      return {
        keyword: route.params.keyword,
        keyword1: route.query.keyword1,
        name: "子心",
        age: 44,
      };
    },
  },
  {
    path: "/login",
    component: Login,
    meta: {
      isHidden: true,
    },
    name: "Login",
  },
  {
    path: "/register",
    component: Register,
    meta: {
      isHidden: true,
    },
    name: "Register",
  },
];

const originalPush = VueRouter.prototype.push; // 先把原来的函数拿下来
const originalReplace = VueRouter.prototype.replace;
// 函数的重写
VueRouter.prototype.push = function push(location, resolve, reject) {
  if (resolve === undefined && reject === undefined) {
    // call、apply、bind
    console.log(location, this);
    return originalPush.call(this, location).catch(() => {});
  } else {
    return originalPush.call(this, location, resolve, reject);
  }
};

VueRouter.prototype.replace = function replace(location, resolve, reject) {
  if (resolve === undefined && reject === undefined) {
    // call、apply、bind
    return originalReplace.call(this, location).catch(() => {});
  } else {
    return originalReplace.call(this, location, resolve, reject);
  }
};

const router = new VueRouter({
  routes,
  mode: "hash",
});

export default router;
